package com.fit.spring.boot.aop.interceptor;

import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.fit.spring.boot.aop.interceptor.autoconfigure.AopInterceptorAutoConfiguration;
import com.fit.spring.boot.aop.notice.Notification;
import com.fit.spring.boot.proxy.interceptor.extension.ProxyExtensionMethodInvocation;

/**
 * 通知拦截器
 * @author hcl
 *
 */
public class NoticeInterceptor implements MethodInterceptor{

	@SuppressWarnings("unchecked")
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object result = null;
		ProxyExtensionMethodInvocation inv = null;
		if(invocation instanceof ProxyExtensionMethodInvocation){
			inv = (ProxyExtensionMethodInvocation)invocation;
		}
		if(inv == null){
			throw new RuntimeException("通知拦截器异常！invocation对象的类型不是ProxyExtensionMethodInvocation！");
		}
		Object param = inv.get(AopInterceptorAutoConfiguration.PARAM_KEY);
		List<Notification> notifs = null;
		if(param != null && param instanceof List){
			notifs = (List<Notification>)param;
		}else{
			if(param == null){
				throw new RuntimeException("通知拦截器异常！没有获取到 '"+AopInterceptorAutoConfiguration.PARAM_KEY+"' 的参数值！");
			}else{
				throw new RuntimeException("通知拦截器异常！'"+param.getClass().getName()+"' 不是一个 '"+List.class.getName()+"'！");
				
			}
		}
		result = invocation.proceed();
		for(Notification notif : notifs){
			result = notif.invoke(result,invocation.getThis().getClass(),invocation.getMethod());
		}
		return result;
	}
}
